#include <stdio.h>
#include <alsa/asoundlib.h>
#include "log.h"
#include "record.h"
#include "AudioQueue.h"
#include "../include/Types.h"
#include "../include/CAEAPI.h"

static CAE_HANDLE handle = NULL;
static FILE* asrFile = NULL ;

/**
** 唤醒回调接口
**/
void test_ivw_fn(const char* pdata, int len, void *userData){
	printf("wake up info = %s\n",pdata);
}

// 这个接口可以忽略
void test_ivw_audio_fn (const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData){
	//printf("test_ivw_audio_fn audioData = %p, audioLen = %d\n", audioData, audioLen);
}

/**
** 降噪后的音频回调(音频格式为16k，16bit，1通道)
**/
void test_recog_audio_fn(const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData)
{
	//printf("test_audio_fn audioData = %p, audioLen = %d\n", audioData, audioLen);
	#if CAEOUT_PCM_SAVE
	 if(NULL == asrFile){
	   char file_name[50];
	   sprintf(file_name , "." "/asr_16k_16bit_1ch.pcm");   asrFile = fopen(file_name,"wb");
	}
	if(NULL == asrFile){
	 printf("open file failed\n");  
	}else{
	// printf("open file success\n");
	}
		
	if(asrFile != NULL){
	   fwrite(audioData,audioLen,1,asrFile);
	}
	#endif
}

static FILE* record_fp = NULL;

/* ------------------------------------------------------------------------
** 多mic音频回调
** ------------------------------------------------------------------------ */
static void record_audio_cb(const void *audio, unsigned int audio_len)
{
	//step3: 将多通道的音频，写入到引擎
	CAEAudioWrite(handle,audio,audio_len);

  #if RECORD_PCM_SAVE
      printf("record audio call back len= %d\n",audio_len);
 
		if (NULL == record_fp){
			  char file_name[50];
			  sprintf(file_name,"." "/record_16k_32bit_6ch.pcm");
			  record_fp = fopen(file_name, "wb");

			 if (NULL == record_fp){
			   LOGE("open file error,file_name = %s, errno = %d",file_name,errno);
			  }else{
			   LOGE("open file ok !");
			  }
		}

		if(record_fp != NULL){
			 fwrite(audio ,  audio_len,1, record_fp);
		}

    #endif
}

int main(int argc ,char** argv){

	const char* conf_path			= "bin/vtn/config/vtn.ini";
	const char* sn = "deb79694-4d15-4737-b269-0293fc03143e" ;

	// step1: 引擎初始化，相关资源的路径必须正确
	int rv = CAENew(&handle, sn, test_ivw_fn, test_ivw_audio_fn, test_recog_audio_fn, conf_path,  NULL);
	if(rv != 0){
	  printf("cae init error %d\n",rv);
	  return -1; 
	}
	
	const char * version  = CAEGetVersion();
	printf("version === %s\n",version);

	//step2: 打开声卡，获取录音。
	REACORD_HANDLE record ;
	int ret = record_start(&record, record_audio_cb);

	if (0 != ret){
		LOGE("record_start failed ret = %d ", ret);
		return -1;
	}

 	printf("engine start success,请对我“小智小智” 唤醒我\n");  
  	while(1){
		sleep(1);
  	}
 	 return 0 ;
}
